<?php

class Calendars extends Controller {
	function __construct(){
		parent::Controller();
		set_include_path(APPPATH . "/libraries");
		require_once 'Zend/Loader.php';
		Zend_Loader::loadClass('Zend_Gdata');
		Zend_Loader::loadClass('Zend_Gdata_AuthSub');
		Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
		Zend_Loader::loadClass('Zend_Gdata_Calendar');
		Zend_Loader::loadClass('Zend_Http_Client');
	}

	function login(){
		// You can convert the single-use token to a session token.
        // Store the session token in our session.
		try{
			$session_token = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
			$this->session->set_userdata('cal_token', $session_token);
			redirect('calendars');
		} catch (Zend_Gdata_App_AuthException $authex){
			echo "Problem authenticating: {$authex->getMessage()}";
		}
	}

	function logout(){
		Zend_Gdata_AuthSub::AuthSubRevokeToken($this->session->userdata('cal_token'));
		$this->session->unset_userdata('cal_token');
		redirect('calendars');
	}

	function index($start = null, $end = null){
		if(!$this->session->userdata("cal_token")){
			// Display link to generate single-use token
		    $googleUri = Zend_Gdata_AuthSub::getAuthSubTokenUri(
		        base_url().'calendars/login/',
		        "http://www.google.com/calendar/feeds/default/private/full", 0, 1);
			$this->load->View('calendars/login', array('uri' => $googleUri));
		    return;
		}

		$start = $start?str_replace('-', '/', $start):"07/01/2010";
		$end = $end?str_replace('-', '/', $end):"12/31/2010";

		$data = array('start' => $start, 'end' => $end);
		$data['calendars'] = $this->_index($start, $end);
		$data['theme'] = "smoothness";
		$this->load->View('calendars/timesheets', $data);
	}

	function _index($start = FALSE, $end = FALSE){
		$client = Zend_GData_AuthSub::getHttpClient($this->session->userdata('cal_token'));

		$service = new Zend_Gdata_Calendar($client);

		$listFeed = null;

		try{
			$listFeed = $service->getCalendarListFeed();
		} catch (Zend_Gdata_App_Exception $e){
			echo "Error: {$e->getMessage()}\n";
		}
		
		$calendars = array();

		if(null !== $listFeed){
			foreach($listFeed as $calendar){
				$cid = explode('/', $calendar->id);
				$cid = $cid[count($cid)-1];
				$ccid = preg_replace('(\W+)', '', $cid);
				//$title = is_object($calendar->title)?$calendar->title->getText():print_r($calendar, true);
				$title = is_object($calendar->title)?$calendar->title->getText():"Error";
				$color = is_object($calendar->color)?$calendar->color->getvalue():"%32ff0000";
				
				$calendars[$ccid] =
					array(
						"id" => $cid,
						"title" => $title, 
						"color" => $color, 
						"events" => array(),
						"total" => 0
					);

				if(FALSE != $start){//If we have a start date, we want events, not just calendars.
					$query = $service->newEventQuery();
					$query->setUser($cid);
					$query->setProjection('full-noattendees');
					$query->setVisibility('private');
					$query->setStartMin(date('Y-m-d', strtotime($start)));
					if(FALSE != $end)//If we have an end date, use it, otherwise unbounded.
					{	$query->setStartMax(date('Y-m-d', strtotime($end)));}
					$query->setMaxResults(100);
					$query->setOrderby('starttime');
					$eventFeed = null;

					try{
						$eventFeed = $service->getCalendarEventFeed($query);
					} catch (Zend_Gdata_App_Exception $e){
						echo "Error: {$e->getMessage()}\n";
					}
					if(null !== $eventFeed){//We got events back.
						$calendars[$ccid]['total'] = 0;
						foreach($eventFeed as $event){
							if(!$event->when[0]){
								continue;
							}
							$eid = explode('/', $event->id->getText());
							$eid = $eid[count($eid)-1];
							$calendars[$ccid]['events'][$eid]['date'] = strtotime($event->when[0]->getStartTime());
							$calendars[$ccid]['events'][$eid]['start'] = strtotime($event->when[0]->getStartTime());
							$calendars[$ccid]['events'][$eid]['end'] = strtotime($event->when[0]->getEndTime());
							$calendars[$ccid]['events'][$eid]['title'] =  $event->title->getText();
							$calendars[$ccid]['events'][$eid]['time'] =  $calendars[$ccid]['events'][$eid]['end'] - $calendars[$ccid]['events'][$eid]['start']; 
							$calendars[$ccid]['total'] += $calendars[$ccid]['events'][$eid]['time'];
						}
					}
				}
			}
		}
		return $calendars;
	}
}
